package ibm.websphere.monitor.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.ContextLoader;

/**
 * <pre>
 * @Description spring上下文管理类，在action中直接使用来获取相关的service
 * </pre>
 *
 * @author ZHOUYANG
 * @date 2010-6-24
 * @time 下午04:37:22
 */



/**
 * <pre>
 * @Description hibanate的daohelper(通用数据库操作接口)实现类
 * </pre>
 *
 * @copyright www.timotai.net
 * @author 这家伙真懒
 * @date 2016-1-12
 */
public class SpringContext {

	private static ApplicationContext ctx ;

	static {
		try {
			ctx = ContextLoader.getCurrentWebApplicationContext();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(ctx == null){
			ctx = new ClassPathXmlApplicationContext("config/spring.xml");
		}

	}

	/**
	 * 获取spring中的bean，通常情况下应该使用 ServiceHelper来获取service对象，而不是本方法
	 * @param name
	 * @return
	 */
	public static Object getBean(String name){
		return ctx.getBean(name);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(Class<T> clazz){
		String[] beanNames = ctx.getBeanNamesForType(clazz);
		if (beanNames != null && beanNames.length > 0) {
			String firstBeanName = beanNames[0];
			return  (T)ctx.getBean(firstBeanName, clazz);
		}
		return null;
	}

	public static ApplicationContext getContext(){
		return ctx;
	}
}
